﻿/**************************************************************
 *
 * 唯一标识：9dd0dace-5508-44ce-998f-289b2bfeb2fa
 * 命名空间：Sgr.DataCategories
 * 创建时间：2023/8/20 16:49:55
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using FluentValidation;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Sgr.BackGroundTasks;
using Sgr.Data;
using Sgr.Data.DatabaseTranslators;
using Sgr.DataCategories.Application.Commands.AdministrativeDivisions;
using Sgr.DataCategories.Application.Commands.DataCategoryItem;
using Sgr.DataCategories.Application.Queries;
using Sgr.DataCategories.Application.Queries.Impl;
using Sgr.DataCategories.Application.Validations.AdministrativeDivisions;
using Sgr.DataCategories.Application.Validations.DataCategoryItem;
using Sgr.DataCategories.BackGroundTasks;
using Sgr.DataCategories.Domain.AdministrativeDivisions;
using Sgr.DataCategories.Domain.DataCategoryItem;
using Sgr.DataCategories.Infrastructure;
using Sgr.DataCategories.Infrastructure.Repositories;
using Sgr.DataCategories.Infrastructure.Sead;
using Sgr.DataCategories.Services;
using Sgr.EntityFrameworkCore;
using Sgr.Modules;
using Sgr.Security.Permissions;

namespace Sgr.DataCategories
{
    public class ModuleStartup : ModuleStartupBase
    {
        public const string RefreshCategoryCacheBackgroundTaskId = "RefreshCategoryCacheTask";

        public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //var categoryItemsManagement = app.ApplicationServices.GetRequiredService<ICategoryItemsManagement>();
            //AsyncHelper.RunSync(() => categoryItemsManagement.PreloadAllAsync());

            //var recurringTaskManager = app.ApplicationServices.GetRequiredService<IRecurringTaskManager>();
            //AsyncHelper.RunSync(() => recurringTaskManager.ReStartAsync(RefreshCategoryCacheBackgroundTaskId));
        }

        public override void ConfigureServices(IServiceCollection services)
        {
            services.TryAddEnumerable(ServiceDescriptor.Singleton<IPermissionProvider, Permissions>());
            services.TryAddEnumerable(ServiceDescriptor.Singleton<IEntityFrameworkTypeProvider, DataCategoriesEntityFrameworkTypeProvider>());

            services.TryAddEnumerable(ServiceDescriptor.Singleton<ICategoryTypeProvider, CategoryTypeProvider>());
            services.TryAddEnumerable(ServiceDescriptor.Singleton<IDataDictionaryProvider, DataDictionaryProvider>());

            RegisterRepositories<SgrDbContext>(services);

            //数据字典
            services.TryAddScoped<IDataCategoryQueries, DataCategoryQueries>();
            services.TryAddScoped<IDataCategoryItemManage, DataCategoryItemManage>();

            services.AddTransient<IValidator<CreateCategpryItemCommand>, CreateCategpryItemCommandValidator>();
            services.AddTransient<IValidator<UpdateCategpryItemCommand>, UpdateCategpryItemCommandValidator>();
            services.AddTransient<IValidator<DeleteCategpryItemCommand>, DeleteCategpryItemCommandValidator>();

            //行政区划
            services.TryAddScoped<IAdministrativeDivisionQueries, AdministrativeDivisionQueries>();
            services.TryAddScoped<IAdministrativeDivisionManage, AdministrativeDivisionManage>();

            services.AddTransient<IValidator<CreateAdministrativeDivisionCommand>, CreateAdministrativeDivisionCommandValidator>();
            services.AddTransient<IValidator<DeleteAdministrativeDivisionCommand>, DeleteAdministrativeDivisionCommandValidator>();
            services.AddTransient<IValidator<UpdateAdministrativeDivisionCommand>, UpdateAdministrativeDivisionCommandValidator>();

            //其它服务
            services.TryAddEnumerable(ServiceDescriptor.Transient<IDataBaseInitialize, DataCategoryDataBaseInitialize>());
            //services.AddTransient<IDataBaseInitialize, DataCategoryItemAreaDataBaseInitialize>();
            //services.AddTransient<IDataBaseInitialize, DataCategoryItemDataBaseInitialize>();

            if (services.Any(f => f.ServiceType == typeof(IAdmDivManagement)))
                services.Replace(ServiceDescriptor.Scoped<IAdmDivManagement, AdmDivManagement>());
            else
                services.AddScoped<IAdmDivManagement, AdmDivManagement>();

            services.AddMediatR(cfg =>
            {
                cfg.RegisterServicesFromAssemblyContaining<ModuleStartup>();
            });

            // 清理资源
            services.TryAddEnumerable(ServiceDescriptor.Scoped<ICleanupHandle, CategoryCacheRefreshHandle>());
            //services.TryAddScoped<RefreshCategoryCacheBackgroundTask>();
            //services.Configure<BackGroundTaskOptions>(opts =>
            //{
            //    opts.RegistRecurringTask<RefreshCategoryCacheBackgroundTask>(
            //       RefreshCategoryCacheBackgroundTaskId,
            //        "每天凌晨5点执行一次字典缓存重置任务",
            //        "0 0 5 * * ?"
            //    );
            //});
        }

        private static void RegisterRepositories<TDbContext>(IServiceCollection services) where TDbContext : UnitOfWorkDbContext
        {
            services.TryAddScoped<IDataCategoryItemRepository, DataCategoryItemRepository<TDbContext>>();
            services.TryAddScoped<IAdministrativeDivisionRepository, AdministrativeDivisionRepository<TDbContext>>();
        }
    }
}